let express = require('express');
let app = express();
let multer = require('multer');
let upload = multer();
let NodeRSA = require('node-rsa');
let CryptoJS = require('crypto-js');

const privateKey = `-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDHHj1EhqJIyU/m
j0S5oOWBrQ2Znsphax29AlKsFPlgeF2Q0XcHZKt9OL/+nADwJNhy/ySPYYa2mLD7
iKlPRd+m26iPEIlX/7axRzYrQFv4KssZqW0z9SaP4k98dB4DoPwOy0OXijPD7sdv
CnBwU0vofW8E7kLQVqawSxWZ7qFirNjl8Aj2cic6N3RpYSiae01gh9AA7UOmOLXU
hIXGM0EcBo4xnDI9VbN8zRh19o02fD+r4d1GMY7k7lnEPYDGFhESCz8yH7LQ6KWm
oyUKmB6EC8O3ulDg36uq9IWi2n7+11cCGSIes9pmZTpOJsDASfCiVnDUvPUUybgw
QAXVgIUZAgMBAAECggEBAI2E1YDFu8PFqM8yVmMkktn2l+ruK+LPUeSLKRz7Dz7c
bYvHBDUx/JxUYEjisdv8JAafhmmNpERVA7zSpZsdC1c5WXTNCQCNU1huR3a4GGWq
bI2BmIbMHys2as4GbWqg2WTeXNzwsdf49q/aGI4M9a94rxYvDTerzm8P/ntYWkWZ
V9zp85+jnYzvt2q4O5U9LbOFzRoOn9u10VN4UtG1DXysoVgBcdqAKSOawfZ1osxR
CmNzgPBKthIl0XSg/mK+hxtAn5WV03bEt7ncZ7LQzwnx+YVB7N88CzbKypR/VyLg
c0+vmxHSlfaaccxrbd4Qvun69B9iTPnMTUtfUwce2wECgYEA9JTcm3UuNLm3bDAC
ti+OYWOhECQGiHLV9epvzV48kx3xc8d7jmWcewLIQR24ZQp2biBm48W+6qT8ek1k
zH9umjxe8eFe2izvrWhoWcf1kGAtCyHmrUDe+iqRFlR0EC9uMlMD5AswddI1g+pA
f3wJBQ3jVX7pa/jaNXXsf61TTDkCgYEA0GoEl0sn1YB3NuvqSVfbBByVURR79zXL
dyrPSYubKf7iW7ABW3oEFvJT6NqYNUZYGfJr+Unc8xG6rxG0t0+t216R45IMq1mS
WE4fnO1uvrAfk8WCBbNxUjvsmlaxr8cWJB34tVlSAbQ+FoAN7HzMiUYTrEkzF95B
7Fo9uXzMv+ECgYEA5us1bkEwou9FUovxw3kbALBD/S1GTcW+ZTQ24rs6jdwTf7Cz
4znkh++UioY49ozuTAOjoSGuo3OqPP6dUMZv8odVTSHvoCYVFLAi9cFpBCsJ3Bzh
4moBHEjcOyz5d96QOEtQvRojYtpZVHby9mpxSahXHv13/U0zGI6B//nxT2ECgYB5
si5UGbJ83LLAAymfAgoFcJtP6OIqC+NvBjRcAYTtFMQgPbnNLIZOz9lnUp0mHpk7
LW8W9aZq2KNlrrUThRdDzQjrFVEIjRkDLzsOayYLetQ1eVLe+VTma89Qn+bJeTrY
hBfB7RIRpKnMgaGfwY+9aIn8RBHtkf50gI0iTllQgQKBgCRwVMLaSBNxGGFdpzFC
CS41R6vmmPhGsFV3VrL9NqcinUNNWrAGqgV6b6royGpidLi3QzAqdbVY/Ed+cMaK
voBkM8OoGOc2E06RQu4ykxyzV6qev1IcHC0mB12WxOHB2e99d6VPQgdHC7jiWa6Y
M6UCxiIYHQgOyARasMZO9rIX
-----END PRIVATE KEY-----`;

//设置跨域访问
app.all('*', (req, res, next) => {
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Credentials", "true");
    res.setHeader("Access-Control-Allow-Methods", "*");
    res.setHeader("Access-Control-Allow-Headers", "Content-Type,Access-Token");//这里“Access-Token”是我要传到后台的内容key  
    res.setHeader("Access-Control-Expose-Headers", "*");
    next();
});

app.post('/test', upload.none(), (req, res) => {
    let key = req.body.key;
    let data = req.body.data;

    // 1. 用RSA解密，获取AES的密钥和向量
    const rsaKey = new NodeRSA(privateKey, 'pkcs8-private-pem', { encryptionScheme: 'pkcs1' });
    let decrypted = rsaKey.decrypt(key, 'utf8');
    try {
        decrypted = JSON.parse(decrypted);
    } catch (e) {
        res.end(JSON.stringify({ code: -1, msg: '错误' }));
        return;
    }

    // 2. 用AES对数据解密
    const aesKey = decrypted.key;
    const aesIv = decrypted.iv;
    const decrypt = CryptoJS.AES.decrypt(data, CryptoJS.enc.Utf8.parse(aesKey), {
        iv: CryptoJS.enc.Utf8.parse(aesIv),
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });
    const msg = CryptoJS.enc.Utf8.stringify(decrypt);

    // 3. 用接收到的AES对返回的数据加密
    var aesEncrypt = CryptoJS.AES.encrypt('you said: ' + msg, CryptoJS.enc.Utf8.parse(aesKey), {
        iv: CryptoJS.enc.Utf8.parse(aesIv),
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });
    var resMsg = aesEncrypt.toString();
    res.end(JSON.stringify({ code: 0, data: resMsg, msg: '成功' }));
});

app.listen(3000, () => {
    console.log('server is start');
})